import { Component, OnInit } from '@angular/core';
import { ActivatedRoute,Router } from '@angular/router';
import { flyIn } from '../../../../animations/fly-in';
import {HttpRequest} from "../../../../service/httpRequest";

declare let $:any;
@Component({
  selector: 'app-assin-products',
  templateUrl: './assin-products.component.html',
  styleUrls: ['./assin-products.component.css'],
  animations: [
    flyIn
  ]
})
export class AssinProductsComponent implements OnInit {

  data = [];
  accountId:string = '';
  selectedpids = [];
  constructor(private httpRequest:HttpRequest,private activeRoute:ActivatedRoute,private router:Router) { }

  ngOnInit() {
    this.activeRoute.params.subscribe(params=>{
      this.accountId = params['accountId'];
      this.getData();
    });
  }


  getData(){
    this.httpRequest.sendGet('products/list',{account_id:this.accountId}).subscribe(res=>{
      this.data = res;
      for(let i=0;i<this.data.length;i++){
        for(let key in this.data[i]){
          if(key=="state"){
            this.selectedpids.push(this.data[i].id);
          }
        }
      }
      $('#treeview-checkable').treeview({
        data:  this.data,
        showIcon: false,
        showCheckbox: true
      });

      $('#treeview-checkable').treeview('expandAll', {silent: true});
    },err=>console.log(err));
  }

  save(){
    let selectedNodes =  $('#treeview-checkable').treeview("getChecked");

    let str = '';
    for (let i = 0;i < selectedNodes.length; i++){
      str += selectedNodes[i].id +';';
    }
    str = str.substring(0, str.length - 1);
    let strarr = str.split(';');
    let arrData = [],delpids = [];
    for(let i in  this.selectedpids){
      arrData[ this.selectedpids[i]] =  this.selectedpids[i]
    }
    for(let i in strarr){
      if(arrData[strarr[i]]){
        delete arrData[strarr[i]]
      }else{
        arrData[strarr[i]] = strarr[i];
      }
    }

    let ttda = [],del_ids='',product_ids='';

    for(let key in arrData){
      delpids.push(arrData[key])
    }
    if(delpids==null||delpids==[]){
      product_ids = '';
      del_ids = ''
    }else{
      for(let i in  this.selectedpids){
        ttda[ this.selectedpids[i]] =  this.selectedpids[i]
      }
      for(let i in delpids){
        if(ttda[delpids[i]]){
          del_ids += ttda[delpids[i]] + ';'
        }else{

          product_ids += delpids[i] + ";"
        }
      }
    }

    this.httpRequest.sendPost('account/productrelate',{
      product_ids:product_ids.substring(0, product_ids.length - 1),
      del_ids:del_ids.substring(0, del_ids.length - 1),
      account_id:this.accountId
    }).subscribe(res=>{
      alert("产品分配成功！");
      this.router.navigateByUrl('page/sys/account/assindevice/'+this.accountId);
    },err=>alert("产品分配失败！"));

  }

}
